import _ from "lodash";
import { typeClassName } from "@/pages/config/classNameMap";

const requireComponent = require.context("./", true, /[A-Z]\w+\.(vue)$/);
const comp = {};
requireComponent.keys().forEach((fileName) => {
  if (fileName != "./index.vue") {
    const componentConfig = requireComponent(fileName);
    const name = componentConfig.default.name;
    const componentName = _.upperFirst(
      _.camelCase(
        name
          .split("/")
          .pop()
          .replace(/\.\w+$/, "")
      )
    );
    comp[componentName] = componentConfig.default || componentConfig;
  }
});
Object.keys(comp).map((key) => {
  comp[key].components = comp;
});
export default {
  components: comp,
  data() {
    return {
      vms: {}, //页面组件vue实例
      models: {
        //模型

        reductionWorkUnit: {
          ...typeClassName["reductionWorkUnit"],
        },
        workNotice: {
          ...typeClassName["workNotice"],
        },
        tank: {
          ...typeClassName["tank"],
        },
        materialRecord: {
          ...typeClassName["materialRecord"],
        },
      },
      onlyRead: false,
      personOptions: [], //  设备下拉选项
      dateOptions: [], // 会计年下拉
      workNoticeId:null,
      dataSet: {
        //数据集
        tableData: [],
        formData: {},
        workTableData:[],
        workUnitData: {},
      },
    };
  },
  provide() {
    return {
      anc: this,
    };
  },
  computed: {},
  created() {
    Object.keys(this.models).map((k) => {
      this.models[k].clz = this.$modelObject.create(this.models[k].modelType);
      this.models[k].clzs = this.$modelObject.create(
        this.models[k].modelType + "Collection"
      );
    });
  },
  mounted() {
    console.log(this.$route);
    this.$nextTick(() => {
      // this.getDateOptions();
      // this.getPersonOptions();

      if (process.env.NODE_ENV === "development") {
        console.log(this);
      }
    });
  },
  methods: {
    /**
     *
     * @param {分页} pageNavigation
     * @param {筛选条件} filter
     * @param {*} orderBy
     * 页面加载方法
     */
    loadPage(pageNavigation, filter) {
      let data = {
        ...filter,
        type: this.models["reductionWorkUnit"].type,
        className: this.models["reductionWorkUnit"].className,
        ...this.leftFilter,
      };

      let fileStr = this._$setFilteStr(data);
      let newFilter = {
        condition: fileStr,
      };

      this.$api.TwinsInstance.queryByPage(
        pageNavigation.pageNumber,
        pageNavigation.pageSize,
        newFilter
      ).then((res) => {
        this.dataSet.workUnitData = res.records[0];
        this.workNoticeId = res.records[0].values.workNoticeId;
        if (this.workNoticeId == null) {
          this.$Message.info("该工位没有运行的工单");
          return;
        }
        this.getWorkNotice(this.workNoticeId);
      });
    },
    getWorkNotice(workNoticeId) {
      this._$queryByIds(this.models.workNotice.clzs, [workNoticeId]).then(
        (flag) => {
          if (flag) {
            let data = this.models.workNotice.clzs.valueRecords[0];
            // this.dataSet.rightTableData =
            //   this.models.workNotice.clzs.valueRecords;
            let parentId = this._$getHierItemField(
              data.hier,
              "records",
              "nodeId"
            );
            let workNotice = data.hier.content.filter(
              (item) => item.parentId == parentId
            );
            let ids = workNotice.map((item) => {
              return item.link.linkId;
            });

            this.feedTable(ids);
          }
        }
      );
    },
    workLoadPage() {
      if (this.workNoticeId == null || this.workNoticeId == "") {
        this.$Message.info("没有工单")
        return
      }
      this._$queryByIds(this.models.workNotice.clzs, [this.workNoticeId]).then((flag) => {
        if (flag) {
          this.dataSet.workTableData =
            this.models.workNotice.clzs.valueRecords;
        }
      });
      // let newFilter = {
      //   ...filter,
      //   className: this.models.workNotice.className,
      //   type: this.models.workNotice.type,
      // };
      // this._$queryByPage(
      //   this.models.workNotice.clzs,
      //   pageNavigation,
      //   newFilter,
      //   filter,
      //   "",
      //   "",
      //   false
      // ).then((flag) => {
      //   if (flag) {
      //     this.dataSet.workTableData =
      //       this.models.workNotice.clzs.valueRecords;
      //   }
      // });
    },
    feedTable(ids) {
      if (ids.length == 0) {
        this.dataSet.tableData = [];
        return;
      }
      this._$queryByIds(this.models.tank.clzs, ids).then((res) => {
        let tableData = this._clone(this.models.tank.clzs.records);
        // tableData.forEach((item, index) => {
        //   // 初始化所有选中状态 为false
        //   item._checked = false;
        //   if (this.dataSet.feedIds.includes(item.id)) {
        //     item._checked = true;
        //   }
        // });
        this.dataSet.tableData = tableData.map((item) => {
          return {
            ...item,
            ...item.values,
          };
        });
      });
    },
    /**
     * 人员管理新增
     */
    handleCreate(row) {
      console.log(row);
      this._modalShow("createModal")
      row.values.weight = row.restCapacity;
      this.dataSet.formData = row;
      // this.onlyRead = false;
      // this.dataSet.formData = this.$modelObject.getTpl(
      //   this.models.reductionWorkUnit.modelType
      // ); // 这是一个整理接口数据JSON格式的方法
    },

    /**
     *
     * @param {*} row
     * 人员管理查看
     */
    handleDetail(row) {
      console.log(row);
      this.vms.detailModal.show = true;
      row.values.if_accountPeriod = String(row.values.if_accountPeriod);
      this.dataSet.formData = row;
      this.onlyRead = true;
    },
    /**
     *
     * @param {*} row
     * 人员管理编辑
     */
    handleEdit(row) {
      this._modalShow("editModal")
      this.vms.editModal.show = true;
      row.values.weight = row.restCapacity;
      this.dataSet.formData = row;
    },
    /**
     *
     * @param {行数据} row
     * @param {索引} index
     * 人员管理删除数据
     */
    handleDelete(row, index) {
      this._$deleteConfirm(() => {
        this._$deleteByIds(this.models.reductionWorkUnit.clzs, [row.id]).then(
          (res) => {
            this.loadPage(this.vms.mainTable.pageNavigation, {}, "", "", false);
          }
        );
      });
    },
    /**
     *
     * @param {行数据} selection
     */
    handleDeleteMultiple(selection) {
      this._$deleteConfirm(() => {
        let ids = selection.map((item) => String(item.id));
        this._$deleteByIds(this.models.reductionWorkUnit.clzs, ids).then(
          (res) => {
            this.loadPage(this.vms.mainTable.pageNavigation, {}, "", "", false);
          }
        );
      });
    },
    addMaterialRecord(data,btn) {
      this.$api.production.addMaterialRecord(data).then((res) => {
        this._modalClose('createModal');
        this._modalClose('editModal');
        btn.loading = false
        this.loadPage(this.vms.mainTable.pageNavigation, {});
      });
      btn.loading = false
    },
    // 创建人员管理提交
    createModalOk(btn) {
      // this.vms.createView.validate((valid) => {
      this._$validateAll([this.vms.createView], (valid) => {
        if (valid) {
          this.dataSet.formData.values.pickStatus = true;
          this.dataSet.formData.values.restCapacity =
            this.dataSet.formData.values.weight;
          this.dataSet.formData.values.tankId = this.dataSet.formData.id;
          delete this.dataSet.formData.id;

          this._merge(this.dataSet.formData, {
            className: this.models.materialRecord.className,
            type: this.models.materialRecord.type,
          });
          let data = {
            materialRecord: {
              className: this.dataSet.formData.className,
              type: this.dataSet.formData.type,
              values: {
                ...this.dataSet.formData.values,
              },
            },
            workUnit: {
              ...this.dataSet.workUnitData,
            },
          };
          this.addMaterialRecord(data,btn);
        } else {
          this.$Message.info("请填写必填内容");
        }
      });
    },

    editModalOk() {
      // if (this.dataSet.formData.values.weight > this.dataSet.formData.restCapacity) {
      //   this.$Message.error("")
      // }
      this._$validateAll([this.vms.editView], (valid) => {
        if (valid) {
          this.dataSet.formData.values.pickStatus = false;
          this.dataSet.formData.values.restCapacity =
            this.dataSet.formData.values.weight;
          this.dataSet.formData.values.tankId = this.dataSet.formData.id;
          delete this.dataSet.formData.id;
          this._merge(this.dataSet.formData, {
            className: this.models.materialRecord.className,
            type: this.models.materialRecord.type,
          });
          let data = {
            materialRecord: {
              className: this.dataSet.formData.className,
              type: this.dataSet.formData.type,
              values: {
                ...this.dataSet.formData.values,
              },
            },
            workUnit: {
              ...this.dataSet.workUnitData,
            },
          };
          this.addMaterialRecord(data);
        } else {
          this.$Message.info("请填写必填内容");
        }
      });
    },
  },
};
